package com.dangdang.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CheckSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //检查session中是否有user
        //1.强转
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //2.获取session
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        //如果sesion中有user则放行 没有则跳转到登录页面
        if(user!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //重定向到登录页面
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.sendRedirect(request.getContextPath()+"/user/login_form.jsp");
        }

    }

    @Override
    public void destroy() {

    }
}
